package com.ruoyi.task.dynamicSched.jdbc;

import com.google.common.collect.Lists;
import com.ruoyi.task.dynamicSched.AbstractSchedulingConfigurer;
import com.ruoyi.task.dynamicSched.ScheduleTaskProperties;
import lombok.RequiredArgsConstructor;

import java.util.List;

// MysqlSchedulingConfigurer
@RequiredArgsConstructor
public class MysqlSchedulingConfigurer extends AbstractSchedulingConfigurer {

    private final MysqlScheduleTaskDao mysqlScheduleTaskDao;

    @Override
    protected List<InternalTaskProperties> loadTaskProperties() throws Exception {
        List<InternalTaskProperties> target = Lists.newArrayList();
        List<ScheduleTaskVo> tasks = mysqlScheduleTaskDao.selectAllTasks();
        if (!tasks.isEmpty()) {
            for (ScheduleTaskVo task : tasks) {
                ScheduleTaskProperties.ScheduleTaskType scheduleTaskType = ScheduleTaskProperties.ScheduleTaskType.fromType(task.getTaskType());
                if (ScheduleTaskProperties.ScheduleTaskType.CRON == scheduleTaskType) {
                    target.add(CronTaskProperties.builder()
                            .taskMethod(task.getTaskMethod())
                            .cronExpression(task.getCronExpression())
                            .timeZone(task.getTimeZone())
                            .taskDescription(task.getTaskDescription())
                            .taskClass(task.getTaskHostClass())
                            .build());
                }
                if (ScheduleTaskProperties.ScheduleTaskType.FIXED_DELAY == scheduleTaskType) {
                    target.add(FixedDelayTaskProperties.builder()
                            .taskMethod(task.getTaskMethod())
                            .intervalMilliseconds(String.valueOf(task.getIntervalMilliseconds()))
                            .initialDelayMilliseconds(String.valueOf(task.getInitialDelayMilliseconds()))
                            .taskDescription(task.getTaskDescription())
                            .taskClass(task.getTaskHostClass())
                            .build());
                }
                if (ScheduleTaskProperties.ScheduleTaskType.FIXED_RATE == scheduleTaskType) {
                    target.add(FixedRateTaskProperties.builder()
                            .taskMethod(task.getTaskMethod())
                            .intervalMilliseconds(String.valueOf(task.getIntervalMilliseconds()))
                            .initialDelayMilliseconds(String.valueOf(task.getInitialDelayMilliseconds()))
                            .taskDescription(task.getTaskDescription())
                            .taskClass(task.getTaskHostClass())
                            .build());
                }
            }
        }
        return target;
    }
}
